const db = uniCloud.database()
module.exports = function() {
	this.getToken = async (city) => {
		try {
			let regionRes = await db.collection("t3ds-region").where({
				'city.value': city
			}).get()
			if (!regionRes.data.length) {
				throw new Error(`未配置city=${city}的区域`)
			}
			// console.log('regionRes', regionRes)
			let region = regionRes.data[0]
			var tokenRes = await db.collection("t3ds-token").where({
				platform: 'weixin',
				appId: region.wxPubConfig.appId
			}).get()
			// console.log('wxpub token', tokenRes)
			let tokenData = tokenRes.data[0]
			if (!tokenData || tokenData.expirationTime < Date.now()) {
				//token过期，重新获取
				let res = await uniCloud.httpclient.request("https://api.weixin.qq.com/cgi-bin/token", {
					data: {
						grant_type: "client_credential",
						appid: region.wxPubConfig.appId,
						secret: region.wxPubConfig.appSecret
					},
					dataType: "json"
				})
				console.log('token res', res)
				if (res.data.errcode) {
					throw new Error(`${res.data.errmsg || '获取token遇到错误'}，errcode: ${res.data.errcode}`);
				}
				let tokenInfo = res.data
				if (tokenData) {
					await db.collection("t3ds-token").doc(tokenData._id).update({
						token: tokenInfo.access_token,
						expirationTime: Date.now() + tokenInfo.expires_in * 1000 / 2 // 过期时间一小时
					})
					tokenData.token = tokenInfo.access_token;
					tokenData.expirationTime = Date.now() + tokenInfo.expires_in * 1000 / 2; // 过期时间一小时
					console.log("token更新成功");
				} else {
					tokenData = {
						platform: 'weixin',
						appId: region.wxPubConfig.appId,
						expirationTime: Date.now() + tokenInfo.expires_in * 1000 / 2, // 过期时间一小时
						token: tokenInfo.access_token
					}
					await db.collection("t3ds-token").add(tokenData);
					console.log("token保存成功");
				}
			}
			return tokenData;
		} catch (e) {
			throw e;
		}
	};
	this.getUserInfo = async (city, openId) => {
		try {
			let tokenInfo = await this.getToken(city)
			let res = await uniCloud.httpclient.request("https://api.weixin.qq.com/cgi-bin/user/info", {
				data: {
					access_token: tokenInfo.token,
					openid: openId
				},
				dataType: "json"
			})
			if (res.data.errcode) {
				throw new Error(`${res.data.errmsg || '获取用户信息遇到错误'}，errcode: ${res.data.errcode}`);
			}
			return res.data;
		} catch (e) {
			throw e;
		}
	};
	this.getUserInfoBatch = async (city, openIds) => {
		try {
			let tokenInfo = await this.getToken(city)
			let res = await uniCloud.httpclient.request(
				"https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" +
				tokenInfo.token, {
					method: "POST",
					data: {
						"user_list": openIds
					},
					contentType: "json",
					dataType: "json"
				})
			if (res.data.errcode) {
				throw new Error(`${res.data.errmsg || '批量获取用户信息遇到错误'}，errcode: ${res.data.errcode}`);
			}
			return res.data.user_info_list;
		} catch (e) {
			throw e;
		}
	};
	this.getUserList = async (city, nextOpenId) => {
		try {
			let tokenInfo = await this.getToken(city)
			let params = {
				access_token: tokenInfo.token
			};
			if (nextOpenId) {
				params.next_openid = nextOpenId;
			}
			let res = await uniCloud.httpclient.request("https://api.weixin.qq.com/cgi-bin/user/get", {
				data: params,
				dataType: "json"
			})
			if (res.data.errcode) {
				throw new Error(`${res.data.errmsg || '获取用户信息遇到错误'}，errcode: ${res.data.errcode}`);
			}
			return res.data;
		} catch (e) {
			throw e;
		}
	};
	this.sendTemplateMsg = async (city, data) => {
		// console.log(data);
		try {
			let tokenInfo = await this.getToken(city)
			// console.log(tokenInfo.token);
			let res = await uniCloud.httpclient.request(
				"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + tokenInfo.token, {
					method: "POST",
					data: data,
					contentType: "json",
					dataType: "json"
				})
			if (res.data.errcode !== 0) {
				throw new Error(`${res.data.errmsg || '获取用户信息遇到错误'}，errcode: ${res.data.errcode}`);
			}
		} catch (e) {
			throw e;
		}
	};
	this.createMenu = async (city, data) => {
		try {
			let tokenInfo = await this.getToken(city)
			let res = await uniCloud.httpclient.request(
				"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + tokenInfo.token, {
					method: "POST",
					data: data,
					contentType: "json",
					dataType: "json"
				})
			if (res.data.errcode !== 0) {
				throw new Error(`${res.data.errmsg || '创建菜单遇到错误'}，errcode: ${res.data.errcode}`);
			}
		} catch (e) {
			throw e;
		}
	};
	this.genQRCode = async (city, {
		sceneId,
		sceneStr,
		forever = true
	}) => {
		if (sceneId && !parseInt(sceneId)) {
			throw new Error("sceneId必须是数字");
		}
		let sId;
		if (sceneId) {
			sId = parseInt(sceneId);
			if (sId < 1 || sId > 100000) {
				throw new Error("场景值必须大于等于1并且小于100000");
			}
		}
		let actionName, actionInfo
		if (forever) {
			actionName = sId ? "QR_LIMIT_SCENE" : "QR_LIMIT_STR_SCENE"
			actionInfo = sId ? {
				"scene": {
					"scene_id": sId
				}
			} : {
				"scene": {
					"scene_str": sceneStr + ''
				}
			}
		} else {
			actionName = sId ? "QR_SCENE" : "QR_STR_SCENE"
			actionInfo = sId ? {
				"scene": {
					"scene_id": sId
				}
			} : {
				"scene": {
					"scene_str": sceneStr + ''
				}
			}
		}
		try {
			let tokenInfo = await this.getToken(city)
			let res = await uniCloud.httpclient.request(
				"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + tokenInfo.token, {
					method: "POST",
					data: {
						"action_name": actionName,
						"action_info": actionInfo
					},
					contentType: "json",
					dataType: "json"
				})
			// console.log("生成公众号二维码", JSON.stringify(res));
			if (!res.data.ticket) {
				throw new Error(`${res.data.errmsg || '生成公众号二维码遇到错误'}，data: ${res.data}`);
			}
			return `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.data.ticket}&_t=${Date.now()}`
		} catch (e) {
			throw e;
		}
	}
}
